package k.cloudzuul.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yc.bean.Result;
import io.jsonwebtoken.Claims;
import k.daimai.util.JwtUtil;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyinfoFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String servletPath = request.getServletPath();
        System.out.println("servletPath = " + servletPath);
        //匹配的才拦截
        return servletPath.matches("/[^/]+/login/myinfo");
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String jwt=request.getHeader("Authorization");
        Result result;
        try {
            Claims claims = JwtUtil.parseJWT(jwt);
            result= new Result(1,"已登陆",claims);
        }catch (Exception e){
            result= new Result(0,"未登录",null);
        }
        //请求不会发送到目标资源
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(200);
        try {
            String json= new ObjectMapper().writeValueAsString(result);
            ctx.getResponse().setContentType("application/json;charset=utf-8");
            ctx.setResponseBody(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
